<?php 
defined('C5_EXECUTE') or die(_("Access Denied."));
class DashboardProjectEstateController extends ProjectEstateDashboardController {

    public $helpers = array('html', 'form');
    
    public function on_start() {
        $subnav = array(array(View::url('/dashboard/project_estate'), t('Project Estate Manage'), true), array(View::url('/dashboard/project_estate/help'), 'Help'));
        $this->set('subnav', $subnav);
        Loader::model('page_list');
		Loader::model('attribute/categories/collection');
        $this->error = Loader::helper('validation/error');
		
		// Project types
		$ak = CollectionAttributeKey::getByHandle('projectestate_types');
        $akc = $ak->getController();
        $options = $akc->getOptions();
        $opts = array();
        foreach ($options as $opt) {
            $opts[$opt->getSelectAttributeOptionID()] = $opt->getSelectAttributeOptionValue();
        }
        $this->set('types', $opts);
		// Project location
		$ak = CollectionAttributeKey::getByHandle('projectestate_locations');
        $akc = $ak->getController();
        $options = $akc->getOptions();
        $opts = array();
        foreach ($options as $opt) {
            $opts[$opt->getSelectAttributeOptionID()] = $opt->getSelectAttributeOptionValue();
        }
        $this->set('locations', $opts);
		// Project Number of Room
		$ak = CollectionAttributeKey::getByHandle('projectestate_numberofrooms');
        $akc = $ak->getController();
        $options = $akc->getOptions();
        $opts = array();
        foreach ($options as $opt) {
            $opts[$opt->getSelectAttributeOptionID()] = $opt->getSelectAttributeOptionValue();
        }
        $this->set('numberofrooms', $opts);
    }
    
    public function view() {
        $this->loadProjectSections();
        $projectList = new PageList();
        $projectList->sortBy('cDateAdded', 'desc');
		if(isset($_GET['ccm_order_by']) && $_GET['ccm_order_by'] == 'cLocation'){
            $projectList->sortbyCollectionAttribute('projectestate_location');			
		}
        if (isset($_GET['cParentID']) && $_GET['cParentID'] > 0) {
            $projectList->filterByParentID($_GET['cParentID']);        
		} 
		else {
            $sections = $this->get('sections');
            $keys = array_keys($sections);
            $keys[] = -1;
            $projectList->filterByParentID($keys);
        }
		$db = Loader::db();
		$columns = $db->MetaColumns(CollectionAttributeKey::getIndexedSearchTable());
		if (isset($columns['AK_EXCLUDE_PAGE_LIST'])) {
			$projectList->filter(false, '(ak_exclude_page_list = 0 or ak_exclude_page_list is null)');
		}
		// filter by language
		if($this->get('lang') == 'vn')
		{
			$projectList->filterByVietnameseMenu(1);
		}
		else
		{
			$projectList->filterByVietnameseMenu(0);
		}
        $this->set('projectList', $projectList);
        $this->set('projectResults', $projectList->getPage());
    }
    
    protected function loadProjectSections() {
        $projectSectionList = new PageList();
        $projectSectionList->filterByProjectestateSection(1);
        $projectSectionList->sortBy('cvName', 'asc');
        $tmpSections = $projectSectionList->get();
        $sections = array();
        foreach ($tmpSections as $_c) {
            $sections[$_c->getCollectionID()] = $_c->getCollectionName();
        }
        $this->set('sections', $sections);
    }

    
    public function edit($cID) {
        $this->setupForm();
        $project = Page::getByID($cID);
        $sections = $this->get('sections');
        
        if (in_array($project->getCollectionParentID(), array_keys($sections))) {
            $this->set('project', $project);
        } else {
            $this->redirect('/dashboard/project_estate/');
        }
    }
    
    public function delete($cID) {
        $this->setupForm();
        $project = Page::getByID($cID);
        $sections = $this->get('sections');
        if (in_array($project->getCollectionParentID(), array_keys($sections))) {
            $this->set('project', $project);
        } else {
            $this->redirect('/dashboard/project_estate/');
        }
    }
    
    protected function setupForm() {
        $this->loadProjectSections();
        Loader::model("collection_types");
        $ctArray = CollectionType::getList('');
        $pageTypes = array();
        foreach ($ctArray as $ct) {
            $pageTypes[$ct->getCollectionTypeID()] = $ct->getCollectionTypeName();
        }
        $this->set('pageTypes', $pageTypes);
        $this->addHeaderItem(Loader::helper('html')->javascript('tiny_mce/tiny_mce.js'));
    }
    
	public function add() {
        $this->setupForm();
        if ($this->isPost()) {
            $this->validate();
            if (!$this->error->has()) {
                $parent = Page::getByID($this->post('cParentID'));
                $ct = CollectionType::getByID($this->post('ctID'));
                $data = array('cName'=>$this->post('projectTitle'), 'cDescription'=>$this->post('projectDescription'), 'cDatePublic'=>Loader::helper('form/date_time')->translate('projectDate'));
				$cProjectPrice = $this->post('projectPrice');
				$cProjectWebsite = $this->post('projectWebsite');
				$cLocationID = $this->post('projectLocation');
				$cTypeID = $this->post('projectType');
				$cNumberOfRoom = $this->post('projectNumberOfRoom');				
				$cLogoID = $this->post('projectLogo');
				
                $p = $parent->add($ct, $data);				
				
				$p->setAttribute('projectestate_logo', $cLogoID);	
				$p->setAttribute('projectestate_type', $cTypeID);
				$p->setAttribute('projectestate_location', $cLocationID);
				$p->setAttribute('projectestate_website', $cProjectWebsite);
				$p->setAttribute('projectestate_price', $cProjectPrice);
				$p->setAttribute('projectestate_numberofroom', $cNumberOfRoom);
                //$rss='<link rel="alternate" type="application/rss+xml" title="'.Loader::helper('text')->entities($p->getCollectionName()).'" href="/'.$this->site($this->rssPageName).'" />';
                //$p->setAttribute('header_extra_content',$rss);
                $this->saveData($p);
				
                $this->redirect('/dashboard/project_estate/', 'project_added');
            }
        }
    }
    
    public function update() {
        $this->edit($this->post('projectID'));
        
        if ($this->isPost()) {
            $this->validate();
            if (!$this->error->has()) {
                $p = Page::getByID($this->post('projectID'));
                $parent = Page::getByID($this->post('cParentID'));
                $ct = CollectionType::getByID($this->post('ctID'));
                $data = array('ctID'=>$ct->getCollectionTypeID(), 'cDescription'=>$this->post('projectDescription'), 'cName'=>$this->post('projectTitle'), 'cDatePublic'=>Loader::helper('form/date_time')->translate('projectDate'));
                $p->update($data);
				$cProjectPrice = $this->post('projectPrice');
				$cProjectWebsite = $this->post('projectWebsite');
				$cLocationID = $this->post('projectLocation');
				$cNumberOfRoom = $this->post('projectNumberOfRoom');
				$cTypeID = $this->post('projectType');
				$cLogoID = $this->post('projectLogo');
				// set language
				if($this->post('lang') == 'vn')
				{
					$p->setAttribute('Vietnamese_menu',1);
				}
				else
				{
					$p->setAttribute('Vietnamese_menu',0);
				}				
				$p->setAttribute('projectestate_logo', $cLogoID);
				$p->setAttribute('projectestate_type', $cTypeID);
				$p->setAttribute('projectestate_location', $cLocationID);
				$p->setAttribute('projectestate_website', $cProjectWebsite);
				$p->setAttribute('projectestate_price', $cProjectPrice);
				$p->setAttribute('projectestate_numberofroom', $cNumberOfRoom);
				
                if ($p->getCollectionParentID() != $parent->getCollectionID()) {
                    $p->move($parent);
                }
                $this->saveData($p);
                $this->redirect('/dashboard/project_estate/', 'project_updated');
            }
        }
    }
    
    public function remove() {
        $this->delete($this->post('projectID'));        
        if ($this->isPost()) {
            $p = Page::getByID($this->post('projectID'));
            $p->delete();
            $this->redirect('/dashboard/project_estate/', 'project_deleted');
        }
    }
    
    protected function validate() {
        $vt = Loader::helper('validation/strings');
        $vn = Loader::Helper('validation/numbers');
        $dt = Loader::helper("form/date_time");
        if (!$vn->integer($this->post('cParentID'))) {
            $this->error->add(t('You must choose a parent page for this Project entry.'));
        }
        
        if (!$vn->integer($this->post('ctID'))) {
            $this->error->add(t('You must choose a page type for this Project entry.'));
        }
        
        if (!$vt->notempty($this->post('projectTitle'))) {
            $this->error->add(t('Title is required'));
        }
        
        if (!$this->error->has()) {
            Loader::model('collection_types');
            $ct = CollectionType::getByID($this->post('ctID'));
            $parent = Page::getByID($this->post('cParentID'));
            $parentPermissions = new Permissions($parent);
            if (!$parentPermissions->canAddSubCollection($ct)) {
                $this->error->add(t('You do not have permission to add a page of that type to that area of the site.'));
            }
        }
    }
    
    private function saveData($p) {
        $blocks = $p->getBlocks('Main');
        foreach ($blocks as $b) {
            $b->deleteBlock();
        }
        
        $bt = BlockType::getByHandle('projectestate_content');
        $data = array('content'=>$this->post('projectBody'));
        $p->addBlock($bt, 'Main', $data);
        Loader::model("attribute/categories/collection");
    }
    
    public function project_added() {
        $this->set('message', t('Project added.'));
        $this->view();
    }
    
    public function project_updated() {
        $this->set('message', t('Project updated.'));
        $this->view();
    }
    
    public function project_deleted() {
        $this->set('message', t('Project deleted.'));
        $this->view();
    }
    
    public function on_before_render() {
        $this->set('error', $this->error);
    }
}
